﻿// Copyright (c) Microsoft Corporation and Contributors.
// Licensed under the MIT License.

using Microsoft.UI.Dispatching;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace SerialCommand
{
    /// <summary>
    /// An empty window that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainWindow : Window
    {
        private ObservableCollection<DeviceListEntry> listOfDevices;
        private Dictionary<DeviceWatcher, String> mapDeviceWatchersToDeviceSelector;
        static public new MainWindow Current;
        private MainConfig mainConfig;
        public MainWindow()
        {
            this.InitializeComponent();
            this.Title = "FAST串口助手";
            Current = this;
            this.Closed += Window_Closed;
            ((FrameworkElement)this.Content).ActualThemeChanged += Window_ThemeChanged;
            mainConfig = MainConfig.GetMainConfig(this);
            mainConfig.ReadConfig();
            mainConfig.SetStyle(BackStyleControl.FastStyle.Mica);
            listOfDevices = new ObservableCollection<DeviceListEntry>();
            mapDeviceWatchersToDeviceSelector = new Dictionary<DeviceWatcher, String>();
        }
        private void Window_Closed(object sender, WindowEventArgs args)
        {
            // Make sure any Mica/Acrylic controller is disposed
            // so it doesn't try to use this closed window.
            mainConfig.SaveConfig();
        }

        private void Window_ThemeChanged(FrameworkElement sender, object args)
        {
            mainConfig.HomeStyle.SetConfigurationSourceTheme(((FrameworkElement)this.Content).ActualTheme);
        }
        public void NotifyUpdate(string message, InfoBarSeverity serverity)
        {
            Notify.Message = message;
            Notify.Severity = serverity;
            Notify.IsOpen = true;
            new Timer((status) => { this.invoke(() => { Notify.IsOpen = false; });}, null, 3000, Timeout.Infinite);
        }

        public void invoke(DispatcherQueueHandler action, DispatcherQueuePriority priority = DispatcherQueuePriority.Normal)
        {
            this.DispatcherQueue.TryEnqueue(priority, () => { action(); });
        }
    }
}
